from google.appengine.api import users
from google.appengine.ext import db
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app

class Beer(db.Model):
  brewery = db.StringProperty(multiline=False)
  beer_name = db.StringProperty(multiline=False)
  stars = db.IntegerProperty()

def beer_key(user):
  return db.Key.from_path('Beer', user.user_id())

class MainPage(webapp.RequestHandler):
  def get(self):
    user = users.get_current_user()

    if not user:
      self.redirect(users.create_login_url(self.request.uri))
      return

    self.response.headers['Content-Type'] = 'text/html'
    self.response.out.write('Hello, %s' % user.nickname())
    self.response.out.write('<br><br>')

    self.response.out.write('<a href="/add">Add</a>')
    self.response.out.write('<br><br>')

    beers = db.GqlQuery('select * from Beer where ancestor is :1 '
                        'order by brewery, beer_name',
			beer_key(user))

    if not beers.count():
      self.response.out.write('No beers saved')

    for beer in beers:
      self.response.out.write('<b>Entry ID:</b> %d ' % beer.key().id())
      self.response.out.write('(<a href="/remove?id=%d">remove</a>)<br>' %
                               beer.key().id())
      self.response.out.write('<b>Brewery:</b> %s<br>' % beer.brewery)
      self.response.out.write('<b>Beer:</b> %s<br>' % beer.beer_name)
      self.response.out.write('<b>Stars:</b> %d<br>' % beer.stars)
      self.response.out.write('<br>')

class AddBeer(webapp.RequestHandler):
  def get(self):
    user = users.get_current_user()

    if not user:
      self.redirect(users.create_login_url(self.request.uri))
      return

    beer = Beer(parent = beer_key(user))
    beer.brewery = "Alagash"
    beer.beer_name = "Curieux"
    beer.stars = 5
    beer.put()

    self.redirect('/') 

class RemoveBeer(webapp.RequestHandler):
  def get(self):
    user = users.get_current_user()

    if not user:
      self.redirect(users.create_login_url(self.request.uri))
      return

    self.response.headers['Content-Type'] = 'text/html'

    beer = Beer.get_by_id(int(self.request.get('id')),
		          parent = beer_key(user))
    if not beer:
      self.response.out.write('No such id=%d?' % int(self.request.get('id')))
      return

    beer.delete()
    self.redirect('/') 


application = webapp.WSGIApplication(
                                     [('/', MainPage),
                                      ('/add', AddBeer),
                                      ('/remove', RemoveBeer)],
                                     debug=True)

def main():
  run_wsgi_app(application)

if __name__ == "__main__":
  main()
